<template>
	<div class="map-canvers-box">
		<div id="map-canvers">
			<div id="map-container" ref="mapContainerRef"></div>
		</div>
		<!-- <div class="map-canvers-box-btn">
            <el-button
                class="screentShotAll"
                @click="captureScreenshot"
                size="small"
            >路径截图</el-button>
            <el-button
                class="screentShotEnd"
                @click="captureScreenshotEnd"
                size="small"
            >终点截图</el-button>
        </div> -->
	</div>
	<!-- <img
        v-if="imageURLRef"
        :src="imageURLRef"
        alt="Map Screenshot"
    /> -->
</template>

<script setup>
	import currentImg from '@/assets/images/currentImg.png';
	import endImg from '@/assets/images/endImg.png';
	import startImg from '@/assets/images/startImg.png';
	import fileInfoHttp from '@/https/fileInfo.js';
	import AMapLoader from '@amap/amap-jsapi-loader';
	import {
		ElMessage
	} from 'element-plus';
	import html2canvas from 'html2canvas';
	import {
		v4 as uuidv4
	} from 'uuid';
	import {
		defineEmits,
		defineProps,
		nextTick,
		onMounted,
		ref,
		watch
	} from 'vue';
	const emits = defineEmits(['closeConfirmMapDriving']);

	let props = defineProps({
		dialogMapInfo: {
			type: Object,
			default: () => {} // 优化默认值为函数，避免引用共享
		},
		logistics: {
			type: Array,
			default: () => [] // 优化默认值为函数
		}
	});

	const mapContainerRef = ref();
	const endMarkerInfo = ref(null);
	const AMapInfo = ref(null);
	const snapshotUrl = ref(null);
	let map = null;
	let AMap = null;
	let pointSegment = []; // 存储分割后的轨迹段
	let allOverlays = ref([]); // 全局收集所有覆盖物（标记点+所有轨迹），用于适配视野

	// 初始化地图
	const initMap = () => {
		nextTick(async () => {
			// 清空历史数据，避免重复绘制
			pointSegment = [];
			allOverlays.value = [];

			// 处理轨迹点，按3公里阈值分割
			if (props.logistics.length <= 1) {
				ElMessage.warning('轨迹点数量不足，无法绘制轨迹');
				return;
			}

			// 过滤无效坐标（经纬度必须为数字且在合理范围）
			const validLogistics = props.logistics.filter(item =>
				typeof item.longitude === 'number' &&
				typeof item.latitude === 'number' &&
				item.longitude >= -180 && item.longitude <= 180 &&
				item.latitude >= -90 && item.latitude <= 90
			);

			if (validLogistics.length <= 1) {
				ElMessage.warning('有效轨迹点不足，无法绘制轨迹');
				return;
			}

			let pointList = validLogistics.map((item) => [item.longitude, item.latitude]);
			console.log('有效坐标点列表:', pointList);

			// 初始化当前轨迹段
			let currentSegment = [pointList[0]];

			// 遍历检测相邻点距离，超过3公里则分割
			for (let i = 0; i < pointList.length - 1; i++) {
				const p1 = {
					longitude: pointList[i][0],
					latitude: pointList[i][1]
				};
				const p2 = {
					longitude: pointList[i + 1][0],
					latitude: pointList[i + 1][1]
				};
				const distance = getDistance(p1, p2); // 计算两点间距离（公里）
				if (distance > 3) { // 超过3公里则分割
					// 完成当前轨迹段（确保至少2个点才添加）
					if (currentSegment.length >= 2) {
						pointSegment.push({
							type: '1', // 实际轨迹段（实线）
							point: [...currentSegment] // 深拷贝，避免引用问题
						});
					}

					// 添加需要规划的间隔段（虚线）
					pointSegment.push({
						type: '2', // 规划轨迹段（虚线）
						point: [
							[p1.longitude, p1.latitude],
							[p2.longitude, p2.latitude]
						]
					});

					// 开始新的轨迹段
					currentSegment = [pointList[i + 1]];
				} else {
					// 距离在3公里内，继续添加到当前轨迹段
					currentSegment.push(pointList[i + 1]);
				}
			}

			// 添加最后一段轨迹（确保至少2个点）
			if (currentSegment.length >= 2) {
				pointSegment.push({
					type: '1',
					point: [...currentSegment]
				});
			}

			console.log('分割后的轨迹段:', pointSegment);

			try {
				AMap = await AMapLoader.load({
					key: 'e52fee918898d366977d9a50cfdc6b7d',
					version: '2.0',
					securityJsCode: 'df3f539c98440733289e8740c0440834',
					plugins: ['AMap.Polyline', 'AMap.Driving', 'AMap.Icon','AMap.Marker'] // 显式加载所有必需插件
				});

				// 初始化地图：不固定zoom，让后续setFitView自动计算
				map = new AMap.Map(mapContainerRef.value, {
					viewMode: '2D',
					center: pointList[0], // 初始中心设为起点
					resizeEnable: true // 启用响应式调整
				});

				// 绘制顺序：先实线 → 再虚线 → 最后适配视野（确保所有覆盖物都已添加）
				setTimeout(() => {
					drivingLine(); // 绘制实线+标记点
				}, 300);

				setTimeout(() => {
					drivingLine2(); // 绘制虚线
				}, 500);

				// 延迟适配视野：确保虚线也绘制完成（关键修复）
				setTimeout(() => {
					fitMapView();
				}, 1500);

			} catch (error) {
				console.error('地图加载失败:', error);
				ElMessage.error('地图加载失败，请刷新重试');
			}
		});
	};

	// 计算两点间距离（公里）- 修复参数传递问题，直接接收两个点对象
	const getDistance = (p1, p2) => {
		const Rad = (d) => (d * Math.PI) / 180.0;
		const radLat1 = Rad(p1.latitude);
		const radLat2 = Rad(p2.latitude);
		const deltaLat = radLat1 - radLat2;
		const deltaLng = Rad(p1.longitude) - Rad(p2.longitude);

		// 地球半径6378.137公里
		const s = 2 * Math.asin(
			Math.sqrt(
				Math.pow(Math.sin(deltaLat / 2), 2) +
				Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)
			)
		) * 6378.137;

		return parseFloat(s.toFixed(2));
	};

	// 绘制规划的虚线轨迹段 - 修复覆盖物收集
	const drivingLine2 = () => {
		try {
			AMap.plugin('AMap.Driving', () => {
				const driving = new AMap.Driving({
					map: map,
					policy: AMap.DrivingPolicy.LEAST_TIME,
					showTraffic: false,
					hideMarkers: true,
					polylineOptions: {
						strokeColor: '#FF0000',
						strokeWeight: 6,
						strokeStyle: 'dashed'
					}
				});

				pointSegment.forEach((item) => {
					if (item.type === '2' && item.point.length === 2) {
						const [startPoint, endPoint] = item.point;
						// 对超过3公里的间隔进行路径规划
						driving.search(startPoint, endPoint, (status, result) => {
							let plannedTrajectory;
							if (status === 'complete') {
								const planRoute = result.routes[0];
								if (planRoute) {
									const planningPath = planRoute.steps.reduce((path, step) => path.concat(step.path), []);

									// 绘制虚线轨迹
									plannedTrajectory = new AMap.Polyline({
										path: planningPath,
										strokeColor: '#ffffff', // 调整虚线颜色，更醒目
										strokeWeight: 5,
										strokeOpacity: 0.9,
										strokeStyle: 'dashed',
										strokeDasharray: [5, 5],
										zIndex: 99 // 虚线层级高于实线，避免被覆盖
									});
								}
							}

							// 规划失败或无路线时，降级为直线虚线
							if (!plannedTrajectory) {
								console.error('路径规划失败，降级为直线虚线:', result);
								plannedTrajectory = new AMap.Polyline({
									path: [startPoint, endPoint],
									strokeColor: '#ff0000',
									strokeWeight: 5,
									strokeOpacity: 0.9,
									strokeStyle: 'dashed',
									strokeDasharray: [5, 5],
									zIndex: 100
								});
							}
							map.add(plannedTrajectory);
							allOverlays.value.push(plannedTrajectory); // 虚线轨迹加入覆盖物列表
						});
					}
				});
			});
		} catch (error) {
			console.error('绘制虚线轨迹错误:', error);
		}
	};

	// 绘制实际轨迹段（实线）- 彻底修复终点图标不显示问题
	const drivingLine = () => {
		try {
			const validLogistics = props.logistics.filter(item =>
				typeof item.longitude === 'number' &&
				typeof item.latitude === 'number'
			);

			if (validLogistics.length >= 2) {
				const list = [...props.logistics];
				const points = list.map((item) => [item.longitude, item.latitude]);
				// 创建标记函数
				const getMarker = (point, image, width = 30, height = 30) => {
					const icon = new AMap.Icon({
						size: new AMap.Size(width, height),
						image,
						imageSize: new AMap.Size(width, height)
					});
					const marker = new AMap.Marker({
						position: [point?.longitude, point?.latitude],
						icon: icon,
						offset: new AMap.Pixel(-width / 2, -height)
					});
					return marker;
				};

				// 存储所有标记点
				const allMarkers = []; // 使用类型断言
				// 起点
				const start = list.shift();
				props.dialogMapInfo.entranceTime = start.createTime;
				const startMarker = getMarker(start, startImg);
				map.add(startMarker);
				allMarkers.push(startMarker);
				const end = list.pop();
				if (props.dialogMapInfo.status == '90' || props.dialogMapInfo.status == '100') {
					const endMarker = getMarker(end, endImg);
					console.log('endendendend', end);
					map.add(endMarker);
					allMarkers.push(endMarker);
					endMarkerInfo.value = endMarker;
				}
				if (props.dialogMapInfo.status == '10') {
					const endMarker = getMarker(end, currentImg);
					map.add(endMarker);
					allMarkers.push(endMarker);
					endMarkerInfo.value = endMarker;
				}
				map.setFitView(allMarkers);

				// 绘制所有实线轨迹段
				pointSegment.forEach((item) => {
					if (item.type === '1' && item.point.length >= 2) {
						const polyline = new AMap.Polyline({
							path: item.point,
							strokeColor: '#3366FF',
							strokeOpacity: 0.9,
							strokeWeight: 6,
							lineJoin: 'round',
							showDir: true, // 显示方向箭头
							zIndex: 0 // 实线层级最低
						});
						map.add(polyline);
						allOverlays.value.push(polyline); // 实线轨迹加入覆盖物列表
					}
				});
			}
		} catch (error) {
			console.error('绘制实线轨迹错误:', error);
		}
	};

	// 地图视野适配 - 核心修复：确保所有覆盖物都被包含
	const fitMapView = () => {
		if (!map || allOverlays.value.length === 0) {
			console.warn('无覆盖物可适配视野');
			return;
		}

		console.log('适配视野的覆盖物数量:', allOverlays.value.length);
		// setFitView参数：覆盖物数组、是否动画、内边距（上下左右各80px，避免贴边）
		map.setFitView(allOverlays.value, true, [80, 80, 80, 80]);

		// 兜底：如果自动适配后zoom过小（比如小于8），强制设置最小zoom
		const currentZoom = map.getZoom();
		if (currentZoom < 8) {
			map.setZoom(8);
			console.log('自动适配zoom过小，强制设置为8');
		}
	};

	// base64转File对象
	const base64ToFile = (base64Data, fileName = 'signature.png') => {
		const arr = base64Data.split(',');
		if (arr.length < 2) throw new Error('无效的base64数据');
		const mime = arr[0].match(/:(.*?);/)[1];
		const bstr = atob(arr[1]);
		let n = bstr.length;
		const u8arr = new Uint8Array(n);

		while (n--) {
			u8arr[n] = bstr.charCodeAt(n);
		}

		return new File([u8arr], fileName, {
			type: mime
		});
	};

	const imageURLRef = ref(null);

	// 截图功能
	const captureScreenshot = async () => {
		capture();
	};

	const captureScreenshotEnd = async () => {
		capture();
	};

	const capture = async () => {
		ElMessage({
			type: 'warning',
			message: '正在保存，请稍后...'
		});

		// 优化截图时机，确保视野适配完成
		setTimeout(() => {
			if (!map) {
				ElMessage.error('地图未加载完成，无法截图');
				return;
			}

			const mapContainer = document.getElementById('map-canvers');
			html2canvas(mapContainer, {
					allowTaint: true,
					useCORS: true,
					scale: 2, // 提高截图分辨率
					backgroundColor: '#ffffff', // 修复透明背景问题
					logging: false
				})
				.then(async (canvas) => {
					const imageUrl = canvas.toDataURL('image/png');
					imageURLRef.value = imageUrl;

					const file = base64ToFile(imageUrl, `${uuidv4()}.png`);
					const formData = new FormData();
					formData.append('file', file);
					formData.append('id', props.dialogMapInfo.id || '');

					try {
						const res = await fileInfoHttp.transferRecordUpload(formData);
						if (res.success) {
							ElMessage({
								type: 'success',
								message: '保存成功'
							});
							emits('closeConfirmMapDriving');
						} else {
							ElMessage.error('保存失败：' + (res.msg || '未知错误'));
						}
					} catch (uploadError) {
						console.error('截图上传失败:', uploadError);
						ElMessage.error('保存失败，请检查网络');
					}
				})
				.catch((e) => {
					console.error('截图失败:', e);
					ElMessage.error('截图失败，请重试');
				});
		}, 3500); // 延长延迟，确保所有绘制和适配完成
	};

	// 监听logistics变化，重新初始化地图（适配动态数据）
	watch(() => props.logistics, (newVal) => {
		if (newVal.length > 1) {
			initMap();
		}
	}, {
		deep: true
	});

	onMounted(async () => {
		initMap();
	});

	defineExpose({
		captureScreenshot
	});
</script>
<style scoped lang="less">
	#map-container {
		height: 600px;
		background-color: var(--cp-bg);
		overflow: hidden;
		position: relative;
		// 确保地图容器不会被其他元素遮挡
		z-index: 1;

		.title {
			background-color: #fff;
			height: 46px;
			width: 355px;
			border-radius: 4px;
			display: flex;
			align-items: center;
			padding: 0 15px;
			font-size: 16px;
			position: absolute;
			left: 10px;
			top: 10px;
			box-sizing: border-box;
			box-shadow: 0px 0px 22px 0px rgba(229, 229, 229, 0.5);
			z-index: 999;

			>span {
				flex: 1;
				text-align: center;
			}

			.van-icon {
				font-size: 18px;
				color: #666;

				&:last-child {
					color: var(--cp-primary);
				}
			}
		}

		.current {
			height: 80px;
			border-radius: 4px;
			background-color: #fff;
			height: 80px;
			width: 355px;
			box-sizing: border-box;
			padding: 15px;
			position: absolute;
			left: 10px;
			bottom: 10px;
			box-shadow: 0px 0px 22px 0px rgba(229, 229, 229, 0.5);
			z-index: 999;

			.status {
				font-size: 15px;
				line-height: 26px;
			}

			.predict {
				color: var(--cp-tip);
				font-size: 13px;
				margin-top: 5px;

				>span {
					padding-right: 10px;
				}
			}
		}

		.screentShotAll {
			position: absolute;
			top: 10px;
			right: 90px;
			z-index: 2000;
		}

		.screentShotEnd {
			position: absolute;
			top: 10px;
			right: 10px;
			z-index: 2000;
		}
	}

	.map-canvers-box {
		position: relative;
		min-height: 600px;

		.map-canvers-box-btn {
			position: absolute;
			top: 10px;
			right: 10px;
		}
	}
</style>